package org.wu.framework.core.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;

public class AnnotatedElementUtils {

    /**
     * 获取 clazz上的注解
     *
     * @param clazz      class
     * @param annotation 注解类型
     * @return Annotation
     */
    public static <A extends Annotation> A getMergedAnnotation(Class<?> clazz, Class<A> annotation) {
        return annotation.cast(clazz.getAnnotation(annotation));
    }

    /**
     * 获取 clazz上的注解
     *
     * @param annotatedElement class
     * @param annotation       注解类型
     * @return Annotation
     */
    public static <A extends Annotation> A findMergedAnnotation(AnnotatedElement annotatedElement, Class<A> annotation) {

//        return annotation.cast(annotatedElement.getAnnotation(annotation));
        // 判断是否有指定类型的注解
        if (AnnotationsScanner.scanHasElementAnnotation(annotatedElement, annotation)) {
            A a = annotation.cast(annotatedElement.getAnnotation(annotation));
            if (a != null) {
                return a;
            }
            // 返回注解的代理对象

            MergedAnnotationElement annotationElement = AnnotationsScanner.scan(annotatedElement);
            return SynthesizedMergedAnnotationElementInvocationHandler.createProxy(annotationElement, annotation);

        } else {
            // 如果没有返回null

            return null;
        }

    }


    /**
     * 验证是否有指定注解
     *
     * @param annotatedElement class
     * @param annotation       注解类型
     * @param <A>              Annotation
     * @return 布尔类型
     */
    public static <A extends Annotation> boolean hasAnnotation(AnnotatedElement annotatedElement, Class<A> annotation) {
        return findMergedAnnotation(annotatedElement, annotation) != null;
    }
}
